// pages/admin/pet-form/pet-form.js
const { get, post, put, upload } = require('../../../utils/request')
const { showSuccess, showError, showConfirm, getImageUrl } = require('../../../utils/util')

Page({
  data: {
    isEdit: false,
    petId: null,
    formData: {
      name: '',
      type: '',
      breed: '',
      age: '',
      gender: '',
      health: '',
      location: '',
      status: '',
      description: ''
    },
    typeIndex: 0,
    typeList: ['请选择类型', '猫', '狗', '其他'],
    genderIndex: 0,
    genderList: ['请选择性别', '公', '母'],
    healthIndex: 0,
    healthList: ['请选择健康状况', '健康', '轻微疾病', '需要治疗', '康复中'],
    statusIndex: 0,
    statusList: ['请选择状态', '待领养', '已领养'],
    imageList: [],
    submitting: false
  },

  onLoad(options) {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    if (options.id) {
      this.setData({
        isEdit: true,
        petId: options.id
      })
      this.loadPetDetail()
    }
  },

  // 加载宠物详情（编辑模式）
  loadPetDetail() {
    get(`/pet/${this.data.petId}`).then(res => {
      const petInfo = res.data
      
      // 处理图片
      let imageList = []
      if (petInfo.images) {
        const images = petInfo.images.split(',').filter(img => img.trim())
        imageList = images.map(img => getImageUrl(img.trim()))
      }

      // 设置选择器索引
      const typeIndex = this.data.typeList.indexOf(petInfo.type) || 0
      const genderIndex = this.data.genderList.indexOf(petInfo.gender) || 0
      const healthIndex = this.data.healthList.indexOf(petInfo.health) || 0
      const statusIndex = this.data.statusList.indexOf(petInfo.status) || 1

      this.setData({
        formData: {
          name: petInfo.name || '',
          type: petInfo.type || '',
          breed: petInfo.breed || '',
          age: petInfo.age ? petInfo.age.toString() : '',
          gender: petInfo.gender || '',
          health: petInfo.health || '',
          location: petInfo.location || '',
          status: petInfo.status || '',
          description: petInfo.description || ''
        },
        typeIndex,
        genderIndex,
        healthIndex,
        statusIndex,
        imageList
      })

      // 设置页面标题
      wx.setNavigationBarTitle({
        title: `编辑宠物 - ${petInfo.name}`
      })

    }).catch(err => {
      showError('加载宠物信息失败')
      wx.navigateBack()
    })
  },

  // 表单输入事件
  onNameInput(e) {
    this.setData({
      'formData.name': e.detail.value
    })
  },

  onBreedInput(e) {
    this.setData({
      'formData.breed': e.detail.value
    })
  },

  onAgeInput(e) {
    this.setData({
      'formData.age': e.detail.value
    })
  },

  onLocationInput(e) {
    this.setData({
      'formData.location': e.detail.value
    })
  },

  onDescriptionInput(e) {
    this.setData({
      'formData.description': e.detail.value
    })
  },

  // 选择器事件
  onTypeChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      typeIndex: index,
      'formData.type': index > 0 ? this.data.typeList[index] : ''
    })
  },

  onGenderChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      genderIndex: index,
      'formData.gender': index > 0 ? this.data.genderList[index] : ''
    })
  },

  onHealthChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      healthIndex: index,
      'formData.health': index > 0 ? this.data.healthList[index] : ''
    })
  },

  onStatusChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      statusIndex: index,
      'formData.status': index > 0 ? this.data.statusList[index] : ''
    })
  },

  // 选择图片
  chooseImage() {
    const remainCount = 5 - this.data.imageList.length

    wx.chooseImage({
      count: remainCount,
      sizeType: ['compressed'], // 选择压缩图片
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 进一步压缩图片
        this.compressImages(res.tempFilePaths)
      }
    })
  },

  // 压缩图片
  async compressImages(tempFilePaths) {
    wx.showLoading({
      title: '处理图片中...',
      mask: true
    })

    try {
      const compressedPaths = []

      for (let i = 0; i < tempFilePaths.length; i++) {
        const filePath = tempFilePaths[i]
        console.log('开始压缩图片:', filePath)

        try {
          const compressedPath = await this.compressImage(filePath)
          compressedPaths.push(compressedPath)
          console.log('图片压缩成功:', compressedPath)
        } catch (err) {
          console.error('图片压缩失败:', err)
          // 如果压缩失败，使用原图片
          compressedPaths.push(filePath)
        }
      }

      this.setData({
        imageList: [...this.data.imageList, ...compressedPaths]
      })
    } catch (err) {
      console.error('图片处理失败:', err)
      wx.showToast({
        title: '图片处理失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 单个图片压缩
  compressImage(filePath) {
    return new Promise((resolve, reject) => {
      wx.compressImage({
        src: filePath,
        quality: 60, // 压缩质量，0-100，数值越小压缩越厉害
        success: (res) => {
          console.log('压缩前大小:', filePath)
          console.log('压缩后大小:', res.tempFilePath)
          resolve(res.tempFilePath)
        },
        fail: (err) => {
          console.error('图片压缩失败:', err)
          reject(err)
        }
      })
    })
  },

  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.imageList[index],
      urls: this.data.imageList
    })
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const imageList = [...this.data.imageList]
    imageList.splice(index, 1)
    this.setData({
      imageList
    })
  },

  // 表单验证
  validateForm() {
    const { name, type, gender, status } = this.data.formData

    if (!name.trim()) {
      showError('请输入宠物名称')
      return false
    }

    if (!type) {
      showError('请选择宠物类型')
      return false
    }

    if (!gender) {
      showError('请选择宠物性别')
      return false
    }

    if (!status) {
      showError('请选择宠物状态')
      return false
    }

    return true
  },

  // 上传图片
  async uploadImages() {
    if (this.data.imageList.length === 0) {
      return ''
    }

    const uploadPromises = this.data.imageList.map(filePath => {
      // 如果是网络图片（编辑模式下的现有图片），直接返回相对路径
      // 只有以我们后端baseUrl开头的才是已上传的图片
      if (filePath.startsWith(getApp().globalData.baseUrl)) {
        const relativePath = filePath.replace(getApp().globalData.baseUrl, '')
        return Promise.resolve({ data: relativePath })
      }
      // 否则上传新图片（包括微信临时文件）
      console.log('准备上传图片:', filePath)
      return upload(filePath, 'file')
    })

    try {
      const results = await Promise.all(uploadPromises)
      console.log('所有图片上传结果:', results)

      const imageUrls = results.map((res, index) => {
        console.log(`处理第${index + 1}张图片结果:`, res)

        // 检查上传结果是否有效
        if (!res || !res.data) {
          console.error(`第${index + 1}张图片上传结果无效:`, res)
          throw new Error(`第${index + 1}张图片上传失败`)
        }

        // 检查是否是临时文件路径（这种情况说明上传失败了）
        if (res.data.includes('tmp/') || res.data.includes('wxfile://')) {
          console.error(`第${index + 1}张图片返回了临时文件路径，上传失败:`, res.data)
          throw new Error(`第${index + 1}张图片上传失败，返回了临时文件路径`)
        }

        // 对于上传的新图片，需要将完整URL转换为相对路径
        if (res.data && res.data.startsWith('http')) {
          const relativePath = res.data.replace(getApp().globalData.baseUrl, '')
          console.log(`第${index + 1}张图片URL转换: ${res.data} -> ${relativePath}`)
          return relativePath
        }

        // 对于已有图片，直接使用相对路径
        console.log(`第${index + 1}张图片使用已有路径:`, res.data)
        return res.data
      }).join(',')

      console.log('最终图片路径字符串:', imageUrls)
      return imageUrls
    } catch (err) {
      console.error('图片上传过程出错:', err)
      throw new Error('图片上传失败: ' + err.message)
    }
  },

  // 提交表单
  async onSubmit() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    this.setData({ submitting: true })

    try {
      // 上传图片
      const images = await this.uploadImages()

      const app = getApp()
      const userInfo = app.globalData.userInfo

      const submitData = {
        name: this.data.formData.name.trim(),
        type: this.data.formData.type,
        breed: this.data.formData.breed.trim(),
        age: this.data.formData.age ? parseInt(this.data.formData.age) : null,
        gender: this.data.formData.gender,
        health: this.data.formData.health,
        location: this.data.formData.location.trim(),
        status: this.data.formData.status,
        description: this.data.formData.description.trim(),
        images,
        userId: userInfo.id,
        userName: userInfo.name
      }

      if (this.data.isEdit) {
        // 编辑模式：在请求体中包含ID，使用PUT /pet
        submitData.id = this.data.petId
        await put('/pet', submitData)
        showSuccess('修改成功')
      } else {
        await post('/pet', submitData)
        showSuccess('添加成功')
      }
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)

    } catch (err) {
      showError(err.message || '保存失败，请重试')
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 取消
  onCancel() {
    wx.navigateBack()
  }
})
